import sys
from threading import Thread, currentThread
import subprocess
from Demo.SwitchButton import SwitchButton

from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QLabel, QHBoxLayout, QLineEdit, QSpacerItem, \
    QSizePolicy, QVBoxLayout, QPlainTextEdit, QFrame
from PyQt5.QtGui import QTextCursor
from PyQt5.QtCore import QObject, pyqtSignal, QTimer

# 定义全局线程类
thread = None


# 自定义信号发射对象
class MySignals(QObject):
    # 设置一个信号源
    log_print = pyqtSignal(str)


class MyCodeWindow(QWidget):
    def __init__(self):
        super().__init__()
        # 创建检查adb设备的定时器
        self.timer = QTimer()

        self.signal = MySignals()

        self.layout_0 = QVBoxLayout()
        self.layout_1 = QHBoxLayout()
        self.layout_2 = QHBoxLayout()
        self.layout_3 = QHBoxLayout()
        self.layout_4 = QHBoxLayout()
        self.layout_5 = QVBoxLayout()
        self.layout_6 = QHBoxLayout()
        self.layout_7 = QHBoxLayout()
        self.layout_8 = QVBoxLayout()

        self.btn_1 = QPushButton('开始')
        self.btn_2 = QPushButton('停止')
        self.btn_3 = QPushButton('清除')
        self.btn_4 = QPushButton('测试按钮')
        # self.btn_5 = SwitchButton(68, 34, color='#1E90FF', open_str='开', close_str='关')
        self.btn_5 = SwitchButton(54, 27, color='green')
        self.h_spider = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)

        self.lab_sn = QLabel('音箱SN码')
        self.lineEdit_sn = QLineEdit()
        self.btn_refresh = QPushButton('复制')

        self.lab_version = QLabel('音箱版本')
        self.lineEdit_version = QLineEdit()
        self.btn_cutdown = QPushButton('停止')

        self.lab_type = QLabel('音箱种类')
        self.lineEdit_type = QLineEdit()
        self.btn_copy = QPushButton('复制')

        self.lab_news = QLabel('实时日志')
        self.v_spider = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.text_edit = QPlainTextEdit()

        # 增加分割线
        self.h_line = QFrame()
        self.h_line.setFrameShape(QFrame.VLine)
        self.h_line.setFrameShadow(QFrame.Sunken)

        self.lab_logs = QLabel('运行记录')
        self.v_spider2 = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.logs_edit = QPlainTextEdit()

        self.h2_spider = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.btn_ok = QPushButton('确定')
        self.btn_exit = QPushButton('退出')

        self.init()

    def init(self):
        self.setWindowTitle('Form')
        self.resize(1000, 700)
        self.lineEdit_sn.setPlaceholderText('请输入SN码')
        # 设置QPlainTextEdit最多显示的行数，这里最多限制1000行
        self.text_edit.setMaximumBlockCount(1000)
        # 设置QPlainTextEdit为只读模式
        self.text_edit.setReadOnly(True)

        # 将自定义信号绑定槽函数
        self.signal.log_print.connect(self.print_log)

        self.layout_1.addWidget(self.btn_1)
        self.layout_1.addWidget(self.btn_2)
        self.layout_1.addWidget(self.btn_3)
        self.layout_1.addWidget(self.btn_4)
        self.layout_1.addItem(self.h_spider)

        self.layout_2.addWidget(self.lab_sn)
        self.layout_2.addWidget(self.lineEdit_sn)
        self.layout_2.addWidget(self.btn_refresh)

        self.layout_3.addWidget(self.lab_version)
        self.layout_3.addWidget(self.lineEdit_version)
        self.layout_3.addWidget(self.btn_cutdown)

        self.layout_4.addWidget(self.lab_type)
        self.layout_4.addWidget(self.lineEdit_type)
        self.layout_4.addWidget(self.btn_copy)

        self.layout_5.addWidget(self.lab_news)
        self.layout_5.addWidget(self.btn_5)
        self.layout_5.addItem(self.v_spider)

        self.layout_8.addWidget(self.lab_logs)
        self.layout_8.addItem(self.v_spider2)

        self.layout_6.addLayout(self.layout_5)
        self.layout_6.addWidget(self.text_edit)
        self.layout_6.addWidget(self.h_line)
        self.layout_6.addLayout(self.layout_8)
        self.layout_6.addWidget(self.logs_edit)

        self.layout_7.addItem(self.h2_spider)
        self.layout_7.addWidget(self.btn_ok)
        self.layout_7.addWidget(self.btn_exit)

        self.layout_0.addLayout(self.layout_1)
        self.layout_0.addLayout(self.layout_2)
        self.layout_0.addLayout(self.layout_3)
        self.layout_0.addLayout(self.layout_4)
        self.layout_0.addLayout(self.layout_6)
        self.layout_0.addLayout(self.layout_7)

        self.setLayout(self.layout_0)

        self.lineEdit_sn.setReadOnly(True)

        # self.text_edit.setTextColor(QColor('yellow'))
        # self.btn_1.clicked.connect(self.task)
        # self.btn_2.clicked.connect(self.close_log)
        self.btn_3.clicked.connect(self.refresh_log_edit)
        self.btn_4.clicked.connect(self.add_html_line)

        # switchButton绑定信号槽函数
        self.btn_5.signal.clicked.connect(self.task)

        self.timer.timeout.connect(self.check_devices)
        self.timer.start(1000)

    def print_log(self, line):
        # 追加文本
        self.text_edit.appendPlainText(line)
        # 获取光标位置
        cursor = self.text_edit.textCursor()
        # 设置光标位置为文本最后
        cursor.movePosition(QTextCursor.End)
        self.text_edit.setTextCursor(cursor)
        # 设置光标一直保持可见
        self.text_edit.ensureCursorVisible()

    def task(self, status):
        def thread_func():
            # 通过Signal 的 emit 触发执行 主线程里面的处理函数
            # emit参数和定义Signal的数量、类型必须一致

            # for i in range(0, 20):
            #     self.signal.log_print.emit(f'输出内容{i}')
            #     time.sleep(2)

            # cmd = 'adb logcat'
            # cmd = 'adb shell tail -F userdata/OrionOSClientSDK.log'
            cmd = 'adb shell tail -F userdata/user.log'
            # cmd = 'python3 /Users/xmly/Desktop/MyReposity/py-qt5-project/Demo/download_log.py'
            s = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

            t = currentThread()
            while getattr(t, "open", True):
                line = s.stdout.readline().decode("utf8", "ignore").strip()
                if len(line):
                    self.signal.log_print.emit(line)

        global thread

        if status:
            thread = Thread(target=thread_func)
            thread.start()
        else:
            if thread is None:
                return
            thread.open = False

    def close_log(self):
        global thread
        if thread is None:
            return
        thread.open = False

    def refresh_log_edit(self):
        self.text_edit.setPlainText('')

    def add_html_line(self):
        self.logs_edit.appendHtml('<font color="red">测试测试</font>')

    def check_devices(self):
        import os
        sn = ''
        buffer = os.popen('adb devices')
        for line in buffer:
            if '\tdevice' in line:
                sn = line.replace('\tdevice', '').strip()
        self.lineEdit_sn.setText(sn)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyCodeWindow()
    qss = 'QPlainTextEdit{background: black;color: yellow; font-family: KaiTi;}'
    window.setStyleSheet(qss)
    window.show()
    sys.exit(app.exec())
